package id

import (
	"hash/fnv"
	"sync"
	"time"
)

var dict = [64]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '_', '-'}
var max uint32 = 4096

var UUID *idFlake

type idFlake struct {
	sequence      uint32
	lastTimestamp uint64
	mu            sync.Mutex
}

func init() {
	UUID = &idFlake{}
}

func (id *idFlake) Gen(t int, tid string) (res string) {
	id.mu.Lock()
	defer id.mu.Unlock()

	var timestamp = uint64(time.Now().UnixMilli())
	var sequence uint32
	if uint64(timestamp) > id.lastTimestamp {
		id.sequence = 0
		id.lastTimestamp = timestamp
	} else {
		id.sequence++
		if id.sequence >= max { // 超过一毫秒内的最大发号数量，则借用下一秒的配额
			id.sequence = 0
			id.lastTimestamp += 1
		}
		// 出现时钟回拨，沿用之前的时间戳，等待物理时钟追上，这里的做法就是不更新 id.lastTimestamp
		timestamp = id.lastTimestamp
		sequence = id.sequence
	}

	// 在这里释放锁，基准测试好5ns左右，但并行测试要差50ns，不知道为什么
	// id.mu.Unlock()

	highBits := (timestamp << 22) | uint64(sequence<<10) | (uint64(t) & 0x3FF)

	// 对会话 ID 计算哈希值
	lowBits := getHash(tid)
	// fmt.Println(highBits)
	return encode(highBits, lowBits)
}

func encode(highBits uint64, lowBits uint32) string {
	var s [16]byte
	var mask uint64 = 0x3F // 0b111111
	var mov uint64 = 58    // 64 位右移 58 位就剩下最高的 6 位
	var idx uint64
	var j int
	for i := 0; i < 10; i++ {
		idx = (highBits >> mov) & mask
		s[j] = dict[idx]

		mov -= 6
		j++
	}

	idx = (highBits<<2 | (uint64(lowBits) >> 30)) & mask
	s[j] = dict[idx]
	j++

	mov = 24
	for i := 0; i < 5; i++ {
		idx = (uint64(lowBits) >> mov) & mask
		s[j] = dict[idx]
		mov -= 6
		j++
	}

	return string(s[:])
}

func getHash(in string) uint32 {
	// 创建一个新的32位FNV-1a哈希对象
	h := fnv.New32a()

	// 向哈希对象写入字符串的字节
	h.Write([]byte(in))

	// 获取计算后的哈希值
	return h.Sum32()
}
